package com.codingke.codingkeplayer.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;

import com.codingke.codingkeplayer.MainActivity;
import com.codingke.codingkeplayer.R;
import com.codingke.codingkeplayer.vo.SearchResult;

import java.util.ArrayList;

/**
 * Created by mingtian on 16-3-18.
 */
public class DownloadDialogFragment extends DialogFragment {
    private SearchResult searchResult;
    private MainActivity mainActivity;
    public static DownloadDialogFragment newInstance(SearchResult searchResult){
        DownloadDialogFragment downloadDialogFragment = new DownloadDialogFragment();
        downloadDialogFragment.searchResult = searchResult;
        return downloadDialogFragment;
    }

    private String[] items;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) getActivity();
        items = new String[]{getString(R.string.download), getString(R.string.cancel)};
    }

    //创建对话框的方法
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
        builder.setCancelable(true);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        downloadMusic();
                        break;
                    case 1:
                        dialog.dismiss();
                        break;
                }
            }
        });
        return builder.show();
    }

    private void downloadMusic() {
        Toast.makeText(mainActivity, "正在下载: " + searchResult.getMusicName(),Toast.LENGTH_SHORT).show();
        DownloadUtils.getsInstance().setListener(new DownloadUtils.OnDownloadListener() {

            @Override
            public void onDownload(String mp3Url) {
                Toast.makeText(mainActivity, "歌曲下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(String error) {
                Toast.makeText(mainActivity, error, Toast.LENGTH_SHORT).show();
            }
        }).download(searchResult);
    }
}
